<template>
  <el-row :gutter="20">
    <el-col :span="24">
      <el-card shadow="always" class="compact-card1">
        <el-form :model="selectuser" class="search-form">
          <el-row :gutter="10">
            <el-col :lg="6">
              <el-form-item label="用户名">
                <el-input v-model="selectuser.username" placeholder="请输入用户名" clearable size="mini"
                          style="width: 60%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="6">
              <el-form-item label="手机号码">
                <el-input v-model="selectuser.phone" placeholder="请输入手机号码" clearable size="mini"
                          style="width: 50%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="12">
              <el-form-item label="注册日期">
                <el-date-picker
                    v-model="selectuser.value1"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    style="width: 70%"
                    size="mini">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item class="search-button">
            <el-button size="small" @click="deleteUsers()">删除</el-button>
            <el-button size="small" @click='selectuser.dialogVisible=true'>添加</el-button>
            <el-button size="small" @click="onSubmit">查询</el-button>
            <el-button size="small" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>






      <!--修改用户弹窗-->
      <el-dialog
          title="修改用户"
          :visible.sync="selectuser.dialogVisible2"
          width="30%"
          :close-on-click-modal="false"
          custom-class="user-dialog">
        <el-form inline:true :model="updataUser" style="height: 300px" label-position="left" :rules="rulesUpdataUser" ref="updataUser">
          <el-form-item label="用户名" label-width="80px" prop="username">
            <el-input
                v-model="updataUser.username"
                autocomplete="off"
                placeholder="请输入用户名"
                clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" label-width="80px" prop="sex">
            <el-select v-model="updataUser.sex" placeholder="请选择性别" style="width: 100%">
              <el-option label="男" value=1></el-option>
              <el-option label="女" value=2></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" label-width="80px" prop="phone">
            <el-input
                v-model="updataUser.phone"
                autocomplete="off"
                placeholder="请输入手机号码"
                clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="selectuser.dialogVisible2=false">取 消</el-button>
          <el-button type="primary" @click="submitForm2()">确 定</el-button>
        </div>
      </el-dialog>







      <!--添加用户弹窗-->
      <el-dialog
          title="添加用户"
          :visible.sync="selectuser.dialogVisible"
          width="30%"
          :close-on-click-modal="false"
          custom-class="user-dialog">
        <el-form inline:true :model="updataUser" style="height: 300px" label-position="left" :rules="rulesUpdataUser" ref="updataUser">
          <el-form-item label="用户名" label-width="80px" prop="username">
            <el-input
                v-model="updataUser.username"
                autocomplete="off"
                placeholder="请输入用户名"
                clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="80px" prop="password">
            <el-input
                v-model="updataUser.password"
                autocomplete="off"
                placeholder="请输入密码"
                show-password
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" label-width="80px" prop="sex">
            <el-select v-model="updataUser.sex" placeholder="请选择性别" style="width: 100%">
              <el-option label="男" value=1></el-option>
              <el-option label="女" value=2></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" label-width="80px" prop="phone">
            <el-input
                v-model="updataUser.phone"
                autocomplete="off"
                placeholder="请输入手机号码"
                clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="selectuser.dialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="submitForm(updataUser)">确 定</el-button>
        </div>
      </el-dialog>
      <el-card shadow="always" class="compact-card2">
        <el-table
            :cell-style="{ height: '50px', 'line-height': '40px' }"
            :header-cell-style="{ height: '50px', 'line-height': '40px' }"
            @selection-change="handleSelectionChange"
            :data="tableData"
            height="400">
          <el-table-column
              type="selection">
          </el-table-column>
          <el-table-column
              prop="time"
              label="注册日期"
              align="center">
          </el-table-column>
          <el-table-column
              prop="id"
              label="用户ID"
              align="center">
          </el-table-column>
          <el-table-column
              prop="username"
              label="用户名"
              align="center">
          </el-table-column>
          <el-table-column
              prop="sex"
              label="性别"
              align="center">
            <template #default="scope">
              {{ scope.row.sex === 2 ? '女' : '男' }}
            </template>
          </el-table-column>
          <el-table-column
              prop="phone"
              label="手机号码"
              align="center">
          </el-table-column>
          <el-table-column
              label="操作"
              align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="submitValue(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteUser(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.selectuser.pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="this.selectuser.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.selectuser.total">
      </el-pagination>
    </el-col>
  </el-row>
</template>
<script>
import axios from "axios"

export default {
  name: "User",
  data() {
    return {
      selectuser: {
        username: '',
        phone: '',
        value1: [],
        pageNum: 1,
        pageSize: 5,
        total: 0,
        dialogVisible: false,
        dialogVisible2: false
      },
      tableData: [{
        username: '',
        sex: '',
        phone: '',
        time: '',
        id: ''
      }],
      arrId: [],
      updataUser: {
        username: '',
        password: '',
        sex: 1,
        phone: '',
        id:null
      },
      rulesUpdataUser:{
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'change'}
            ],
        phone: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur'}
            ],
        }
      }
  },
  methods: {
    // 查询用户
    onSubmit() {
      axios.get('/user', {
        params: {
          username: this.selectuser.username,
          phone: this.selectuser.phone,
          startTime: this.selectuser.value1[0],
          endTime: this.selectuser.value1[1],
          pageNum: this.selectuser.pageNum,
          pageSize: this.selectuser.pageSize,
        }
      }).then(response => {
        console.log(response.data)
        this.tableData = response.data.data.list
        this.selectuser.total = response.data.data.total

      }).catch(error => {
        console.log(error)
      })
    },
    // 重置表单
    resetForm() {
      this.selectuser.username = ''
      this.selectuser.phone = ''
      this.selectuser.value1 = []
      this.onSubmit()
    },// 分页大小改变时触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.selectuser.pageSize = val
      this.onSubmit()
    },
    // 分页当前页改变时触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.selectuser.pageNum = val
      this.onSubmit()
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.arrId = [];
      for (let i = 0; i < val.length; i++) {
        this.arrId.push(val[i].id)
      }
      console.log(this.arrId)
    },

    submitForm() {
      this.$refs['updataUser'].validate((valid) => {
        if (valid) {
          this.userAdd()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 添加用户
    userAdd() {
      console.log(this.updataUser)
      axios.post('/user/add', this.updataUser).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.selectuser.dialogVisible = false
          this.onSubmit()
        } else {
          this.$message.error(response.data.msg)
        }
      }).catch(error => {
        console.log(error)
      })
      // 重置属性
      this.selectuser.dialogVisible = false
      this.updataUser.username = ''
      this.updataUser.password = ''
      this.updataUser.sex = 1
      this.updataUser.phone = ''
    },
    submitForm2() {
      this.$refs['updataUser'].validate((valid) => {
        if (valid) {
          this.userRevise()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 编辑用户
    userRevise() {
      axios.post('/user/update', this.updataUser).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.selectuser.dialogVisible2 = false
          this.onSubmit()
        } else {
          this.$message.error(response.data.msg)
          }
      }
      ).catch(error => {
        console.log(error)
      })
    },
    submitValue(row){
      this.selectuser.dialogVisible2 = true
      this.updataUser.username = row.username
      this.updataUser.password = row.password
      this.updataUser.sex = row.sex
      this.updataUser.phone = row.phone
      this.updataUser.id = row.id
    },
    // 删除多个用户
    deleteUsers() {
      this.$confirm('此操作将永久删除id为' + this.arrId + '用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.get('/user/deletes?ids=' + this.arrId).then(response => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              onClose: () => {
                this.selectuser.pageNum = 1
                this.onSubmit()
              },
              message: '删除成功!',

            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除单个用户
    deleteUser(row) {
      this.$confirm('此操作将永久删除id为' + row.id + '用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.get('/user/delete?id=' + row.id).then(response => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              onClose: () => {
                this.selectuser.pageNum = 1
                this.onSubmit()
              },
              message: '删除成功!',

            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  created() {
    this.onSubmit()
  }
}
</script>
<style scoped>
.search-form {
  padding: 10px;
}

.search-button {
  display: flex;
  justify-content: flex-start;
  margin-top: 10px
}

.search-button {
  margin-left: 10px
}

.compact-card1 {
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  height: 150px;
}

.compact-card2 {
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  height: 400px;
}



</style>

